package com.ruoyi.controller;

import com.alibaba.druid.filter.AutoLoad;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.domain.Audit;
import com.ruoyi.enumutil.AuditEnum;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.service.AuditService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.security.Security;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import java.util.*;


/**
 * 超级管理员审核表
 */
@RestController
@RequestMapping("/admin/audit")
public class AdminAuditController {

    //审核
    @Resource
    private AuditService auditService;

    //用户
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 查询审核数据
     * @param page 分页
     * @param audit 条件
     * @return 结果
     */
    @PostMapping("/page")
    public AjaxResult page(@RequestBody Page<Audit> page,@RequestBody Audit audit){
//        System.out.println(page.getSize() + "ssssssssssssss" + page.getCurrent() + audit);
        //查询数据
        auditService.page(page,new LambdaQueryWrapper<Audit>()
                //内容
                .like(StringUtils.isNotBlank(audit.getContent()),Audit::getContent,audit.getContent())
                //审核状态
                .eq(Objects.nonNull(audit.getAuditStatus()),Audit::getAuditStatus,audit.getAuditStatus())
                //逻辑删除
                .eq(Audit::getDeleteFlag,Boolean.FALSE)
        );
        //设置总行数
        page.setTotal(auditService.count(new LambdaQueryWrapper<Audit>()
                //内容
                .like(StringUtils.isNotBlank(audit.getContent()),Audit::getContent,audit.getContent())
                //审核状态
                .eq(Objects.nonNull(audit.getAuditStatus()),Audit::getAuditStatus,audit.getAuditStatus())
                //逻辑删除
                .eq(Audit::getDeleteFlag,Boolean.FALSE)
        ));
        //遍历数据
        page.getRecords().forEach(ele->{
            //判断用户编号不为 null
            if (Objects.nonNull(ele.getUserId())){
                //查询用户
                SysUser sysUser = sysUserMapper.selectUserById(ele.getUserId());
                //设置用户
                if (Objects.nonNull(sysUser)) ele.setSysUser(sysUser);
            }
        });
//        System.out.println(page.getTotal() + "这是我的总行数==========");
        //返回结果
        return AjaxResult.success(page);
    }

    /**
     * 整体修改方法
     * @param audit 修改对象
     * @return 返回结果
     */
    @PostMapping("/update")
    public AjaxResult update(@RequestBody Audit audit){
        //设置默认值
        audit.setUpdateBy(SecurityUtils.getUsername());
        audit.setUpdateTime(new Date());
        //修改
        boolean update = auditService.updateById(audit);
        //返回结果
        return update == Boolean.TRUE ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
    }


    /**
     * 审核通过
     * @param id 主键id
     * @return 返回结果
     */
    @PostMapping("/audit/success/{id}")
    public AjaxResult success(@PathVariable(value = "id")Long id){
        //执行修改
        boolean update = auditService.update(null, new UpdateWrapper<Audit>().lambda()
                //主键
                .eq(Audit::getId, id)
                //审核通过
                .eq(Audit::getAuditStatus, AuditEnum.ShenHeTongGuo.getAuditStatus())
        );
        //返回结果
        return update == Boolean.TRUE ? AjaxResult.success("审核通过") : AjaxResult.error("修改失败");
    }



    /**
     * 审核不通过
     * @param id 主键
     * @return 返回结果
     */
    @PostMapping("/audit/error/{id}")
    public AjaxResult error(@PathVariable(value = "id")Long id){
        //执行修改
        boolean update = auditService.update(null, new UpdateWrapper<Audit>().lambda()
                //主键
                .eq(Audit::getId, id)
                //审核通过
                .eq(Audit::getAuditStatus, AuditEnum.ShenHeBuTongGuo.getAuditStatus())
        );
        //返回结果
        return update == Boolean.TRUE ? AjaxResult.success("审核不通过") : AjaxResult.error("修改失败");
    }


    /**
     * 删除
     * @param id 主键id
     * @return 返回结果
     */
    @PostMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable(value = "id")Long id){
//        System.out.println(id + "我是删除的id");
        //删除
        boolean delete = auditService.removeById(id);
        //返回结果
        return delete == Boolean.TRUE ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }


    /**
     * 新增
     * @param audit 新增对象
     * @return 返回结果
     */
    @PostMapping("/insert")
    public AjaxResult insert(@RequestBody Audit audit){
        //设置默认值
        audit.setCreateBy(SecurityUtils.getUsername());
        audit.setCreateTime(new Date());
        audit.setUpdateBy(SecurityUtils.getUsername());
        audit.setUpdateTime(new Date());
        audit.setDeleteFlag(Boolean.FALSE);
        audit.setUserId(SecurityUtils.getUserId());
        audit.setAuditStatus(AuditEnum.DaiShenHe.getAuditStatus());
        //添加
        boolean insert = auditService.save(audit);
        //返回结果
        return insert == Boolean.TRUE ? AjaxResult.success("添加成功") : AjaxResult.error("添加失败");
    }


    @Resource
    private SysPermissionService permissionService;

    /**
     * 详细数据
     * @return 返回结果
     */
    @GetMapping("/get/detail")
    public AjaxResult getDetail(){
        Set<String> roles = permissionService.getRolePermission(SecurityUtils.getLoginUser().getUser());

        boolean hasSysGroupPermission = roles.contains("sys::group");
        boolean hasAdminPermission = roles.contains("admin");
        //创建map集合
        Map<String,Integer> map = new HashMap<>();
        //总提交
        map.put("total",auditService.count(new LambdaQueryWrapper<Audit>()
                //用户编号
                .eq(hasSysGroupPermission == Boolean.FALSE && hasAdminPermission == Boolean.FALSE,Audit::getUserId,SecurityUtils.getUserId())
                //逻辑删除
                .eq(Audit::getDeleteFlag,Boolean.FALSE)
        ));
        //待审核
        map.put("auditTotal",auditService.count(new LambdaQueryWrapper<Audit>()
                //用户编号
                .eq(hasSysGroupPermission == Boolean.FALSE && hasAdminPermission == Boolean.FALSE,Audit::getUserId,SecurityUtils.getUserId())
                //待审核
                .eq(Audit::getAuditStatus,AuditEnum.DaiShenHe.getAuditStatus())
                //逻辑删除
                .eq(Audit::getDeleteFlag,Boolean.FALSE)
        ));
        //审核通过
        map.put("auditShenHeTongGuo",auditService.count(new LambdaQueryWrapper<Audit>()
                //用户编号
                .eq(hasSysGroupPermission == Boolean.FALSE && hasAdminPermission == Boolean.FALSE,Audit::getUserId,SecurityUtils.getUserId())
                //待审核
                .eq(Audit::getAuditStatus,AuditEnum.ShenHeTongGuo.getAuditStatus())
                //逻辑删除
                .eq(Audit::getDeleteFlag,Boolean.FALSE)
        ));
        //审核不通过
        map.put("auditShenHeBuTongGuo",auditService.count(new LambdaQueryWrapper<Audit>()
                //用户编号
                .eq(hasSysGroupPermission == Boolean.FALSE && hasAdminPermission == Boolean.FALSE,Audit::getUserId,SecurityUtils.getUserId())
                //待审核
                .eq(Audit::getAuditStatus,AuditEnum.ShenHeBuTongGuo.getAuditStatus())
                //逻辑删除
                .eq(Audit::getDeleteFlag,Boolean.FALSE)
        ));
        //返回结果
        return AjaxResult.success(map);
    }


    /**
     * 折线图数据
     * @return 返回结果
     */
    @PostMapping("/api/audit/statistics")
    public List<DailyAuditStatistics> getRecentAuditStatistics() {
        Set<String> roles = permissionService.getRolePermission(SecurityUtils.getLoginUser().getUser());

        boolean hasSysGroupPermission = roles.contains("sys::group");
        boolean hasAdminPermission = roles.contains("admin");
        System.out.println(hasAdminPermission + "jfhalfjla" + hasSysGroupPermission);
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取最近7天的日期，从最早到最新
        List<LocalDate> last7Days = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            last7Days.add(today.minusDays(6 - i)); // 从最早的日期开始添加
        }
        // 查询未删除的审核记录
        List<Audit> audits = auditService.list(new LambdaQueryWrapper<Audit>()
                .eq(Audit::getDeleteFlag, Boolean.FALSE)
                .ge(Audit::getCreateTime, Date.from(today.minusDays(7).atStartOfDay(ZoneId.systemDefault()).toInstant()))
                .eq(hasSysGroupPermission == Boolean.FALSE && hasAdminPermission == Boolean.FALSE,Audit::getUserId,SecurityUtils.getUserId()));
        // 只查询最近7天的数据
        // 将数据按日期分组，并统计每个日期的数量
        Map<String, Long> statistics = audits.stream()
                .collect(Collectors.groupingBy(audit -> {
                    Date createTime = audit.getCreateTime();
                    LocalDate localDate = createTime.toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDate();
                    return localDate.toString(); // 返回日期字符串
                }, Collectors.counting()));
        // 创建一个结果列表
        List<DailyAuditStatistics> result = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 遍历最近7天的日期，构建结果
        for (LocalDate date : last7Days) {
            String dateString = date.format(formatter);
            Long count = statistics.getOrDefault(dateString, 0L); // 获取对应日期的审核数量
            result.add(new DailyAuditStatistics(dateString, count)); // 添加到结果列表
        }
        return result; // 返回结果列表
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class DailyAuditStatistics{
        private String date; // 日期
        private Long count; // 审核数量
    }

}
